package com.bupt.service.system.impl;

import com.alibaba.druid.util.StringUtils;
import com.bupt.config.interceptor.thread.CurrentUserInfo;
import com.bupt.constants.InitConstants;
import com.bupt.constants.ResponseResult;
import com.bupt.dao.TbSystemUserMapper;
import com.bupt.dto.sys.LoginUserDto;
import com.bupt.dto.sys.UserDto;
import com.bupt.exception.BaseException;
import com.bupt.model.TbSystemUser;
import com.bupt.model.TbSystemUserExample;
import com.bupt.service.system.SysLoginService;

import com.bupt.utils.PassWordUtils;
import com.bupt.utils.RedisUtils;
import com.bupt.utils.TokenUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service("sysLoginService")
public class SysLoginServiceImpl implements SysLoginService {

    @Resource
    private RedisTemplate<String, UserDto> redisTemplate;
     @Resource
     private TbSystemUserMapper tbSystemUserMapper;
    @Resource
     private CurrentUserInfo userInfo;
    /**
     * 用户登录业务实现
     * @param username
     * @param password
     * @return
     * @throws BaseException
     */

    @Override
    public Object Login(String username, String password) throws BaseException {
        TbSystemUserExample tbSystemUserExample = new TbSystemUserExample();
         tbSystemUserExample.createCriteria().andUserNameEqualTo(username);
        UserDto userDto = tbSystemUserMapper.selectUserDtoByUserName(username);
        System.out.println(userDto);
        if(userDto!=null){
            String passwordSalt = userDto.getPasswordSalt();
            String dbPassWord = PassWordUtils.getDbPassWord(password, passwordSalt);
            if(StringUtils.equals(dbPassWord,userDto.getUserPassword())){
                String token= UUID.randomUUID().toString();
                //存到redis数据库
                RedisUtils.setObjectByOriKey(token,redisTemplate,userDto);
                TbSystemUser tbSystemUser = new TbSystemUser();
                tbSystemUser.setuId(userDto.getUId());
                tbSystemUser.setLastLoginToken(token);

                tbSystemUserMapper.updateByPrimaryKeySelective(tbSystemUser);
                HashMap<String, Object> map = new HashMap<>();
                map.put("token",token);
                return map;
            }else{
                throw new BaseException("密码错误");
            }
        }else{
            throw new BaseException("用户不存在");
        }
    }

    /**
     * 获取当前用户业务实现
     * @return
     * @throws BaseException
     */
    @Override
    public Object getCurrentLoginUser(UserDto userDto,HttpServletRequest request) throws BaseException {
        userDto = userInfo.getCurrentOptUser();
       return new LoginUserDto(userDto.getUId(),userDto.getUserName(),0);
    }

    /**
     * 用户登出业务实现
     * @param request
     * @return
     * @throws BaseException
     */
    @Transactional(rollbackFor = BaseException.class)
    @Override
    public Object quitCurrentUser(UserDto userDto,HttpServletRequest request) throws BaseException {
        String token = TokenUtils.getTokenFromHeaderOrRequestParamOrCookie(request);
        /*
        查询redis所有的键值
        Set<String> keys = redisTemplate.keys("*");
        for (String key : keys) {
            System.out.println(key);
        }*/
        if (userDto!= null) {
            //解析登录的用户
            System.out.println("userDto:"+userDto);
            TbSystemUser tbSystemUser = new TbSystemUser();
            tbSystemUser.setuId(userDto.getUId());
            tbSystemUser.setLastLoginToken(UUID.randomUUID().toString());
            System.out.println(tbSystemUser.toString());
            try {
                tbSystemUserMapper.updateByPrimaryKeySelective(tbSystemUser);
                RedisUtils.expireObjectByOriKey(token, redisTemplate);
            } catch (BaseException e) {
                throw new BaseException("用户退出失败");
            }
            return InitConstants.OK_MESSAGE;
        } else{
            throw new BaseException("您还未登录，请先登录");
        }
        }

    /**
     * 获取所有可操作的用户
     * @return
     * @throws BaseException
     */
    @Override
    public Object getAllUsers() throws BaseException {
        List<UserDto> allUsers = tbSystemUserMapper.getAllUsers();
        return allUsers;
    }

}
